package problems.contest;

import java.util.HashSet;

/**
 * 第 315 场周赛
 * <p>https://leetcode.cn/contest/weekly-contest-315</p>
 *
 * @author habitplus
 * @since 14:59, 2022/10/16
 */
public class WCT315 {
    /**
     * T1. 与对应负数同时存在的最大正整数
     * <p>https://leetcode.cn/problems/largest-positive-integer-that-exists-with-its-negative/</p>
     */
    public int findMaxK(int[] nums) {
        HashSet<Integer> set = new HashSet<>();

        for (int num : nums) set.add(num);

        int ret = -1;

        for (int num : nums) {
            if (num > 0 && ret < num && set.contains(-1 * num)) {
                ret = num;
            }
        }

        return ret;
    }

    /**
     * T2. 反转之后不同整数的数目
     * <p>https://leetcode.cn/problems/count-number-of-distinct-integers-after-reverse-operations/</p>
     */
    public int countDistinctIntegers(int[] nums) {
        HashSet<Integer> set = new HashSet<>();

        for (int num : nums) set.add(num);
        int k;
        for (int num : nums) {
            k = 0;
            while (num > 0) {
                k = k * 10 + num % 10;
                num /= 10;
            }

            if (k > 0) set.add(k);
        }

        return set.size();
    }

    /**
     * T3. 反转之后的数字和
     * <p>https://leetcode.cn/problems/sum-of-number-and-its-reverse/</p>
     */
    public boolean sumOfNumberAndReverse(int num) {
        if (num <= 1) return num == 0;

        int n = num / 2;
        int re;
        int og;

        for (int i = n; i < num; ++i) {
            re = 0;
            og = i;
            while (og > 0) {
                re = re * 10 + og % 10;
                og /= 10;
            }

            if (re + i == num) return true;
        }

        return false;
    }


    /**
     * T4. 统计定界子数组的数目
     * <p>https://leetcode.cn/problems/count-subarrays-with-fixed-bounds/</p>
     */
    public long countSubarrays(int[] nums, int minK, int maxK) {
        long ans = 0L;
        int n = nums.length,
                minIdx = -1,
                maxIdx = -1,
                ex = -1;

        for (int i = 0; i < n; ++i) {
            if (nums[i] == minK) minIdx = i;
            if (nums[i] == maxK) maxIdx = i;
            if (nums[i] < minK || nums[i] > maxK) ex = i; // 子数组不能包含 nums[ex]
            ans += Math.max(Math.min(minIdx, maxIdx) - ex, 0);
        }
        return ans;
    }
}
